from twisted.spread import pb
from ChessController import MultiPlayerController

class pbChessController(MultiPlayerController, pb.Referenceable):
        
    def notifyOpponent(self, movetext):
        self.opponent.callRemote("notify", movetext)

    def remote_notify(self, movetext):
        self.notify(movetext)

class gameGiver(pb.Root):
    def __init__(self, NWChessControl):
        self.controller = NWChessControl
    
    def remote_acceptGame(self, avatar):
        if self.controller:
            c = self.controller
            c.setOpponent(avatar)
            self.controller = None
            return c
    
if __name__ == "__main__":
    import wx
    from ChessBoard.ChessBoard import ChessBoard
    from twisted.internet import wxreactor
    wxreactor.install()
    from twisted.internet import reactor

    app = wx.PySimpleApp()
    size = (128,128)
    frame = wx.Frame(None, wx.ID_ANY, "Chess Frame")
    controller1 = pbChessController(frame, size)
    controller2 = pbChessController(frame, size)
    controller1.setColor(ChessBoard.WHITE)
    controller2.setColor(ChessBoard.BLACK)
    controller1.setOpponent(controller2)
    controller2.setOpponent(controller1)
    controller2.Flip()
    
    sizer = wx.BoxSizer(wx.HORIZONTAL)
    sizer.Add(controller1,1,wx.EXPAND)
    sizer.Add(controller2,1,wx.EXPAND)
    frame.SetSizer(sizer)
    frame.Fit()
    frame.SetSize((807,400))
    frame.Show()
    
    reactor.registerWxApp(app)
    
    root = gameGiver(controller1)
    reactor.listenTCP(8800, pb.PBServerFactory(root))
    
    factory = pb.PBClientFactory()
    reactor.connectTCP("localhost", 8800, factory)
    
    d = factory.getRootObject()
    d.addCallback(lambda object: object.callRemote("acceptGame",controller2))
    d.addCallback(controller2.setOpponent)

    reactor.run()